/*
 * C/C++ KLIB Project
 * 
 * Copyright (c) 2012 Ken Zhang (cpp.china@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 */


#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int openlog(const char *filename)
{
	int handle = _open(filename, _O_CREAT | _O_WRONLY | _O_APPEND);
	return handle;
}

int logln(int handle, const char *s)
{
	struct tm *lt;
	time_t t;
	char buffer[32];

	if (handle < 0)
		return -1;

	time(&t);
	lt = localtime(&t);
	sprintf(buffer, "[%04d-%02d-%02d %02d:%02d:%02d] ", lt->tm_year + 1900, lt->tm_mon, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);

	if (_write(handle, buffer, strlen(buffer)) < 0)
		return -1;
	
	if (_write(handle, s, strlen(s)) < 0)
		return -1;
	
	strcpy(buffer, "\r\n");
	if (_write(handle, buffer, strlen(buffer)) < 0)
		return -1;
	
	return 0;
}

int loglnf(int handle, const char *fmt, ...)
{
	char *buffer = NULL;
	int n;
	va_list args;

	if (handle < 0)
		return -1;

	va_start(args, fmt);
	n = _vscprintf(fmt, args) + 1;
	buffer = (char *)malloc(n);

	if (buffer != NULL) {
		vsprintf(buffer, fmt, args);
		n = logline(handle, buffer);
		free(buffer);
		return n;
	}

	return -1;
}
